package com.xywy.bloodandroid.fragment;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.xywy.bloodandroid.R;
import com.xywy.bloodandroid.act.LoginAct;
import com.xywy.bloodandroid.act.MyAddNumberActivity;
import com.xywy.bloodandroid.act.MyCollectActivity;
import com.xywy.bloodandroid.act.MyInfoActivity;
import com.xywy.bloodandroid.act.QuestionListAct;
import com.xywy.bloodandroid.act.SettingActivity;
import com.xywy.bloodandroid.bean.User;
import com.xywy.bloodandroid.util.Constants;
import com.xywy.bloodandroid.util.HttpClientUploadTask;
import com.xywy.bloodandroid.util.ImageLoader;
import com.xywy.bloodandroid.util.ImageUtil;
import com.xywy.bloodandroid.util.UIUtil;
import com.xywy.bloodandroid.util.HttpClientUploadTask.HttpClientUploadResponse;
import com.xywy.bloodandroid.util.ImageLoader.ImageCallback;
import com.xywy.bloodandroid.vollery.OnVolleyResponseListener;
import com.xywy.bloodandroid.vollery.PostRequest;
import com.xywy.bloodandroid.vollery.VolleyManager;
import com.xywy.bloodandroid.widget.ClipIconPopupWindow;

/**
 * *****************************************
 * 
 * @Title: PersonalFragment.java
 * @Package com.xywy.bloodandroid.fragment
 * @Description: TODO(个人中心)
 * @author smz
 * @date 2014-12-23 下午2:00:46
 * @version V1.0
 ******************************************* 
 */
public class PersonalFragment extends Fragment implements OnClickListener {

	private Button btn_login; // 马上登录
	private LinearLayout ll_jiahao_mine; // 我的加号
	private LinearLayout ll_collect_mine; // 我的收藏
	private LinearLayout ll_info_mine; // 我的信息
	private LinearLayout ll_message_mine; // 消息
	private LinearLayout ll_setting_mine; // 设置

	private String[] sex = { "男", "女" };
	private ImageView myself_head;
	private TextView is_login_tv;
	private BroadcasrReciver receiver;
	String TAG = "PersonalFragment";

	private View.OnClickListener itemsOnClick = new View.OnClickListener() {

		public void onClick(View v) {
			window.dismiss();
			switch (v.getId()) {
			case R.id.btn_me_infor_clip_photo: // 拍照
				String sdStatus = Environment.getExternalStorageState();
				if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
					Toast.makeText(getActivity(), "未检测到内存卡", Toast.LENGTH_SHORT)
							.show();
					return;
				}
				Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				// 下面这句指定调用相机拍照后的照片存储的路径
				takePicturePath = IMAGE_FILE_PATH + "/IMG"
						+ System.currentTimeMillis() + ".jpg";
				System.out.println("获取的 相册的路径是多少呢   ..." + takePicturePath);
				File image = new File(takePicturePath);
				intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image));
				startActivityForResult(intent2, 2);
				if (window != null) {
					window.dismiss();
				}
				break;
			case R.id.btn_me_infor_clip_album: // 相册选择
				Intent intent = new Intent(Intent.ACTION_PICK, null);
				intent.setDataAndType(
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
				takePicturePath = getActivity().getIntent().getStringExtra(
						"data");
				startActivityForResult(intent, 1);
				if (window != null) {
					window.dismiss();
				}
				break;
			default:
				break;
			}
		}
	};
	private ClipIconPopupWindow window;
	private TextView tv_nick_str;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_mine, null);
		initView(view);
		initListener();
		initdata();
		return view;
	}

	private void initView(View view) {
		btn_login = (Button) view.findViewById(R.id.btn_login);
		ll_jiahao_mine = (LinearLayout) view.findViewById(R.id.ll_jiahao_mine);
		ll_collect_mine = (LinearLayout) view
				.findViewById(R.id.ll_collect_mine);
		ll_info_mine = (LinearLayout) view.findViewById(R.id.ll_info_mine);
		ll_message_mine = (LinearLayout) view
				.findViewById(R.id.ll_message_mine);
		ll_setting_mine = (LinearLayout) view
				.findViewById(R.id.ll_setting_mine);

		is_login_tv = (TextView) view.findViewById(R.id.is_login_tv);
		myself_head = (ImageView) view.findViewById(R.id.myself_head);
		tv_nick_str = (TextView) view.findViewById(R.id.tv_nick_str);
		loader = new ImageLoader();

	}

	private void changehead() {
		Drawable cachedImage = loader.loadDrawable(
				User.getInstance(getActivity()).getAvatar(), myself_head,
				new ImageCallback() {

					@Override
					public void imageLoaded(Drawable imageDrawable,
							ImageView imageView, String imageUrl) {
						if (imageView != null && imageDrawable != null) {
							imageView.setBackgroundDrawable(imageDrawable);
						}
					}
				});

		if (cachedImage == null) {
			myself_head.setBackgroundResource(R.drawable.head);
		} else {
			myself_head.setBackgroundDrawable(cachedImage);
		}
	}

	private void initListener() {
		btn_login.setOnClickListener(this);
		ll_jiahao_mine.setOnClickListener(this);
		ll_collect_mine.setOnClickListener(this);
		ll_info_mine.setOnClickListener(this);
		ll_message_mine.setOnClickListener(this);
		ll_setting_mine.setOnClickListener(this);

		myself_head.setOnClickListener(this);
	}

	private void initdata() {
		IntentFilter filter = new IntentFilter("is_login_sucessful");
		receiver = new BroadcasrReciver();
		getActivity().registerReceiver(receiver, filter);

		if (User.getInstance(getActivity()).getIs_log_sucess()) {
			btn_login.setVisibility(View.GONE);
			is_login_tv.setVisibility(View.GONE);
			myself_head.setVisibility(View.VISIBLE);
			tv_nick_str.setVisibility(View.VISIBLE);
			tv_nick_str
					.setText(User.getInstance(getActivity()).getAccountstr());
			changehead();
		} else {
			btn_login.setVisibility(View.VISIBLE);
			is_login_tv.setVisibility(View.VISIBLE);
			myself_head.setVisibility(View.GONE);
		}

	}

	public class BroadcasrReciver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Message msg = Message.obtain();
			if ("is_login_sucessful".equals(intent.getAction())) {
				if (User.getInstance(getActivity()).getIs_log_sucess()) {
					btn_login.setVisibility(View.GONE);
					is_login_tv.setVisibility(View.GONE);
					myself_head.setVisibility(View.VISIBLE);
					// myself_head.setBackgroundResource(R.drawable.head);
					changehead();
				}

			}
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_login:
			// showToast("跳转到登录页面");
			Intent intent = new Intent(getActivity(), LoginAct.class);
			getActivity().startActivity(intent);
			break;
		case R.id.ll_jiahao_mine:
			if (intentInflitar()) {
				openActivity(MyAddNumberActivity.class);
			}
			break;
		case R.id.ll_collect_mine:
			if (intentInflitar()) {
				openActivity(MyCollectActivity.class);
			}
			break;
		case R.id.ll_info_mine:
			if (intentInflitar()) {
				openActivity(MyInfoActivity.class);
			}
			break;
		case R.id.ll_message_mine:
			// openActivity(MessageActivity.class);
			if (intentInflitar()) {
				openActivity(QuestionListAct.class);
			}
			break;
		case R.id.ll_setting_mine:
			if (intentInflitar()) {
				openActivity(SettingActivity.class);
			}
			break;
		case R.id.myself_head:
			clipIcon();
			break;

		default:
			break;
		}

	}

	private void clipIcon() {
		window = new ClipIconPopupWindow(getActivity(), itemsOnClick);
		// 显示窗口
		// window.showAtLocation(findViewById(R.id.ll_me_infor), Gravity.CENTER
		// , 0, 0); // 设置layout在PopupWindow中显示的位置
		window.show();
	}

	boolean intentInflitar() {
		String userID = User.getInstance(getActivity()).getUserid();
		if (userID == "") {
			openActivity(LoginAct.class);
			showToast("请先登录");
			return false;
		} else {
			return true;
		}

	}

	void showToast(String content) {
		Toast.makeText(getActivity(), content, Toast.LENGTH_SHORT).show();
	}

	void openActivity(Class<?> cls) {
		Intent intent = new Intent(getActivity(), cls);
		startActivity(intent);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		getActivity().unregisterReceiver(receiver);
	}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 150);
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);
	}

	private String takePicturePath;
	private String IMAGE_FILE_PATH = Environment.getExternalStorageDirectory()
			.getAbsolutePath() + "/head_pic";

	private File iconFile;

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Log.i(TAG, "裁剪是否有返回 onActivityResult requestCode：" + requestCode);
		System.out.println("获取的data的返回 ......" + data);
		if (resultCode == getActivity().RESULT_OK) {
			switch (requestCode) {
			// 如果是直接从相册获取
			case 1:
				startPhotoZoom(data.getData());
				// myself_head.setImageURI(data.getData());
				break;
			// 如果是调用相机拍照时
			case 2:

				// takePicturePath = IMAGE_FILE_PATH + "/IMG"
				// + System.currentTimeMillis() + ".jpg";
				// System.out.println("获取相册的路径。。。。"+takePicturePath);
				// ;//takePicturePath
				// startPhotoZoom(Uri.fromFile(temp));

				String outDirectory = Environment.getExternalStorageDirectory()
						.getAbsolutePath()
						+ File.separator
						+ "xywy"
						+ File.separator + "head";

				filePath = ImageUtil.compressImage(takePicturePath,
						outDirectory, 500, 500);

				sendMsg();
				// myself_head.setImageURI(Uri.fromFile(temp));//data.getData()
				break;
			// 取得裁剪后的图片
			case 3:
				System.out.println("获取的data的返回 ......" + data);
				if (data != null) {
					Log.i(TAG, "裁剪是否有返回 onActivityResult data不为空");
					setPicToView(data);
				}
				break;
			default:
				break;
			}
		}
	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpClientUploadResponse.SUCESS:
				System.out.println("成功的返回修改头像" + msg.obj.toString());
				change(msg.obj.toString());
				break;
			case HttpClientUploadResponse.ERROR:
				System.out.println(msg.obj.toString());
				UIUtil.DissDialog(getActivity(), waittingDialog);
				UIUtil.showToast(getActivity(), "你的网速有点慢哦");
				break;

			default:
				break;
			}
		};
	};

	private void change(final String image_url) {
		String url = "http://api.wws.xywy.com/index.php?act=kbb&fun=resetProperty";
		PostRequest<String> request = new PostRequest<String>(url,
				String.class, new OnVolleyResponseListener<String>() {

					@Override
					public void onError(VolleyError volleyError) {
						// TODO Auto-generated method stub
						UIUtil.DissDialog(getActivity(), waittingDialog);
						UIUtil.showToast(getActivity(), "你的网速有点慢哦");

					}

					@Override
					public void onSuccess(String response) {
						// TODO Auto-generated method stub
						UIUtil.DissDialog(getActivity(), waittingDialog);
						try {
							JSONObject json = new JSONObject(response);
							int state = json.optInt("state");
							if (state == 200) {
								Toast.makeText(getActivity(), "更改头像成功",
										Toast.LENGTH_SHORT).show();

								User.getInstance(getActivity()).setAvatar(
										image_url);
								// myself_head.setImageBitmap(bitmap);
								System.out.println("上传头像的的结果..." + image_url);
								changehead();

							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
		HashMap<String, String> params = new HashMap<String, String>();
		try {
			params.put("sign",
					com.xywy.bloodandroid.util.MD5.md5s(Constants.Sign + "wjk"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		params.put("value", image_url);
		params.put("userid", User.getInstance(getActivity()).getUserid());
		// tag=wjk, keyword=avatar
		params.put("tag", "wjk");
		params.put("keyword", "avatar");
		request.setParams(params);
		request.setIsParseJson(false);
		VolleyManager.addRequest(request, getActivity());
	}

	protected ProgressDialog waittingDialog;

	public void waitingDialog(Context context, String message) {
		if (waittingDialog == null)
			waittingDialog = new ProgressDialog(context);
		waittingDialog.setCanceledOnTouchOutside(false);// �����಻��ʧ
		waittingDialog.setMessage(message);
		waittingDialog.show();
	};

	private void sendMsg() {
		waitingDialog(getActivity(), "正在上传");
		final String upUrl = "http://api.wws.xywy.com/upload_avatar.php";
		new Thread(new HttpClientUploadTask(upUrl, handler, filePath, ""))
				.start();
	}

	private String filePath;
	/**
	 * 保存裁剪之后的图片数据
	 * 
	 * @param picdata
	 */
	private Bitmap bitmap;
	private ImageLoader loader;

	private void setPicToView(Intent picdata) {
		Bundle extras = picdata.getExtras();
		if (extras != null) {
			bitmap = extras.getParcelable("data");
			// userIcon.setImageBitmap(bitmap);
			FileOutputStream b = null;
			iconFile = new File(IMAGE_FILE_PATH);
			iconFile.mkdirs();
			filePath = IMAGE_FILE_PATH + "/" + System.currentTimeMillis()
					+ ".jpg";
			try {
				b = new FileOutputStream(filePath);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
				// 上传到服务端
				sendMsg();

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					b.flush();
					b.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
				// myself_head.setImageBitmap(bitmap);
			}
		}
	}
}